package cn.bone.mqtt.demo03;

import cn.bone.mqtt.demo02.Client;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * Created by MD-01 on 2017/4/24.
 */
public class Client01 {

    private static Logger logger = LoggerFactory.getLogger(Client01.class);

    public static void main(String[] args) throws MqttException {
        //String host = "tcp://127.0.0.1:61613";
//        String host = "tcp://127.0.0.1:1883";
        String host = "tcp://172.16.252.234:1883";
        MqttClient client = new MqttClient(host,"clientId-01",
                new MqttDefaultFilePersistence("d:/mqtt"));

        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName("admin");
        options.setPassword("password".toCharArray());
        //false:服务端不清除session,true:服务端清除session
        options.setCleanSession(false);
        //设置自动重新连接
        options.setAutomaticReconnect(false);
        options.setWill("client/disOnline","client01,disOnline".getBytes(),2,true);

        client.setCallback(new DemoCallBack());
        client.connect(options);
        client.subscribe("topic/client-01",2);
        client.subscribe("topic/all",2);
        new Thread(()->{
            while(true){
                if(client.isConnected()){
                    logger.info("客户端连接正常");
                }else{
                    logger.info("客户端断开连接");
                    try {
                        client.connect(options);
                        client.subscribe("topic/client-01",2);
                        client.subscribe("topic/all",2);
                    } catch (MqttException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
